package com.example.bm.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bm.system.pojo.UserModel;
import com.example.bm.system.service.UserService;
import com.example.common.exception.ServiceException;
import com.example.dao.mapper.TUserMapper;
import com.example.dao.mapper.TUserRoleMapper;
import com.example.dao.model.TUser;
import com.example.dao.model.TUserRole;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 用户service
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements UserService {


    @Resource
    private TUserRoleMapper tUserRoleMapper;

    /**
     * 查询列表, 自定义分页
     *
     * @param params
     * @return
     */
    @Override
    public Page<TUser> getPageList(Map<String, Object> params, int pageNum, int pageSize) {
        return PageHelper.startPage(pageNum, pageSize).doSelectPage(() -> this.baseMapper.findList(params));
    }

    /**
     * 不分页
     *
     * @param params
     * @return
     */
    @Override
    public List<TUser> getList(Map<String, Object> params) {
        return this.baseMapper.findList(params);
    }


    /**
     * 新增
     *
     * @param info
     */
    @Override
    @Transactional
    public void createInfo(TUser info, Map<String, String> params) {
        if (StrUtil.isBlank(info.getLoginName())) {
            throw new ServiceException("登录名为空");
        }
        if (StrUtil.isBlank(params.get("roleId"))) {
            throw new ServiceException("未分配角色");
        }

        //校验重复
        LambdaQueryWrapper<TUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TUser::getLoginName, info.getLoginName().trim());
        if (this.count(wrapper) > 0) {
            throw new ServiceException("登录名已存在");
        }

        this.save(info);
        Long roleId = Convert.toLong(params.get("roleId"));
        //保存角色
        TUserRole userRole = TUserRole.builder().roleId(roleId).userId(info.getId()).build();
        tUserRoleMapper.insert(userRole);

    }

    /**
     * 更新
     *
     * @param info
     */
    @Override
    @Transactional
    public void updateInfo(TUser info, Map<String, String> params) {
        this.saveOrUpdate(info);

        //删除用户管理菜单
        LambdaQueryWrapper<TUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TUserRole::getUserId, info.getId());
        tUserRoleMapper.delete(wrapper);

        //保存用户角色
        Long roleId = Convert.toLong(params.get("roleId"));
        TUserRole userRole = TUserRole.builder().roleId(roleId).userId(info.getId()).build();
        tUserRoleMapper.insert(userRole);
    }


    @Override
    @Transactional
    public void deleteInfo(TUser info) {
        //删除用户
        this.removeById(info.getId());

        //删除用户管理菜单
        LambdaQueryWrapper<TUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TUserRole::getUserId, info.getId());
        tUserRoleMapper.delete(wrapper);
    }


    public void getUserModel(String loginName) {
        //校验重复
        LambdaQueryWrapper<TUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TUser::getLoginName, loginName);
        List<TUser> list = this.getBaseMapper().selectList(wrapper);
        if (CollectionUtil.isEmpty(list)) {
            throw new ServiceException("用户不存在");
        }
        UserModel userModel = new UserModel();
        BeanUtils.copyProperties(list.get(0), userModel);

        //查询用户角色
        TUserRole role = tUserRoleMapper.selectOne(new LambdaQueryWrapper<TUserRole>()
                .eq(TUserRole::getUserId, userModel.getId()));
        userModel.setRoleId(role.getRoleId());
        //userModel.setRoleName();
    }
}
